package com.gucheng.service.impl;

import com.gucheng.common.ResponseResult;
import com.gucheng.config.QiniuOSSConfig;
import com.gucheng.exception.SystemException;
import com.gucheng.model.enums.AppHttpCodeEnum;
import com.gucheng.service.UploadService;
import com.gucheng.utils.PathUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

@Service
public class UploadServiceImpl implements UploadService {


    @Autowired
    private QiniuOSSConfig qiniuOSSConfig;

    @Override
    public ResponseResult upload(MultipartFile img) {
        // 判断文件类型

        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //对原始文件进行判断
        String[] allowedExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp"};
        if (!Arrays.stream(allowedExtensions).anyMatch(originalFilename::endsWith)) {
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        // 如果判断通过上传文件到OSS
        String filePath = PathUtils.generateFilePath(originalFilename);
        String url = uploadOss(img, filePath);
        return ResponseResult.okResult(url);
    }



    private String uploadOss(MultipartFile imgFile, String filePath) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);

//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;
        try {
            InputStream inputStream = imgFile.getInputStream();
            Auth auth = Auth.create(qiniuOSSConfig.getAccessKey(), qiniuOSSConfig.getSecretKey());
            String upToken = auth.uploadToken(qiniuOSSConfig.getBucket());
            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "http://sj9ptzyln.hn-bkt.clouddn.com/"+key;
            } catch (QiniuException ex) {
                ex.printStackTrace();
                if (ex.response != null) {
                    System.err.println(ex.response);

                    try {
                        String body = ex.response.toString();
                        System.err.println(body);
                    } catch (Exception ignored) {
                    }
                }
            }
        } catch (Exception ex) {
            //ignore
        }
         return "www";
    }
}
